package com.example.authority.controller;
import com.alibaba.excel.EasyExcel;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.time.LocalDateTime;

import com.example.authority.service.UserService;
import com.example.authority.service.UsermounthlogService;
import com.example.authority.entity.User;
import com.example.authority.service.MouthlogService;
import com.example.authority.service.SharebitService;
import com.example.authority.entity.Mouthlog;
import com.example.authority.entity.Usermounthlog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @program:   
 * @ClassName:MouthlogController
 * @description: MouthlogController前端控制器
 *       
 * @Version 3.0
 **/
@Tag(name = "月审记录 前端控制器")
@RestController
@RequestMapping("/mouthlog")
public class MouthlogController {

@Resource
private MouthlogService mouthlogService;
@Resource
private UserService userService;
@Resource
private SharebitService sharebitService;
@Resource
private UsermounthlogService usermounthlogService;

/**
 * 新增
 * @param mouthlog
 * @return
 */
@Operation(summary = "新增")
@PostMapping
public Result save(@RequestBody Mouthlog mouthlog){
        return Result.success(mouthlogService.save(mouthlog));
        }
/**
* 修改
*
* @param mouthlog
* @return
*/
@Operation(summary = "修改")
@PutMapping("/{id}")
public Result update(@PathVariable Long id,@RequestBody Mouthlog mouthlog) {
        return Result.success(mouthlogService.updateById(mouthlog));
        }

/**
 * 查询所有Mouthlog
 * @return
 */
@Operation(summary = "查询所有Mouthlog")
@GetMapping
public Result findAll(){
        return Result.success(mouthlogService.list());
        }
/**
  * 获取单个
  * @param id
  * @return
  */
@Operation(summary = "获取单个")
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id){
        return Result.success(mouthlogService.getById(id));
        }
/**
 * 分页显示
 * @param
 * @param pageNum
 * @param pageSize
 * @return
 */
@Operation(summary = "分页显示")
@GetMapping("/page")
public Result findPage(
        @RequestParam(defaultValue = "") Long uid,
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize){

        LambdaQueryWrapper<Mouthlog>queryWrapper=new LambdaQueryWrapper();
        if (uid!=null&&uid!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Mouthlog::getUid,uid);
        }

        queryWrapper.orderByDesc(Mouthlog::getId);
        Page<Mouthlog>page=mouthlogService.page(new Page<>(pageNum,pageSize),queryWrapper);
        List<Mouthlog > records = page.getRecords();
         for (Mouthlog mouthlog : records) {
                 User user = userService.getById(mouthlog.getUid());
                 if (ObjectUtil.isNotEmpty(user)){
                     mouthlog.setUser(user);
                 }
         }
         page.setRecords(records);
         return Result.success(page);

        }
/**
* 单个删除
* @param id
* @return
*/
@Operation(summary = "单个删除")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
        return Result.success(mouthlogService.removeById(id));
        }
/**
* 批量删除
* @param ids
* @return
*/
@Operation(summary = "批量删除")
@DeleteMapping("/batch/{ids}")
@Transactional
public Result deleteByIds(@PathVariable String[]ids){
        return Result.success(mouthlogService.removeByIds(Arrays.asList(ids)));
        }

/**
 * 批量导出
 * 使用的技术为alibaba下面的easyexcel
 * 写数据
 *
 * @param ids
 * @return
 */
@Operation(summary = "批量导出")
@GetMapping("/batch/export/{ids}")
public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Mouthlog> list = mouthlogService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("mouthlog导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Mouthlog.class).sheet("sheel1").doWrite(list);

        }

/**
 * 批量导入
 * 使用的技术为alibaba下面的easyexcel
 * 读数据
 *
 * @param
 */
@Operation(summary = "批量导入")
@PostMapping("/batch/upload")
public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Mouthlog.class, new PageReadListener<Mouthlog>(dataList -> {
        dataList.forEach(entity -> mouthlogService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
        }

@GetMapping("/actionMounthChack")
public Result actionMounthCheck(@RequestParam Long id) {
    // 获取最后一条月审记录
    LambdaQueryWrapper<Mouthlog> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.orderByDesc(Mouthlog::getCreateTime);
    queryWrapper.last("LIMIT 1");
    Mouthlog lastMouthlog = mouthlogService.getOne(queryWrapper);
    // 检查是否本月已经审核过
    if (lastMouthlog != null) {
        LocalDateTime lastReviewTime = lastMouthlog.getCreateTime();
        LocalDateTime now = LocalDateTime.now();
        if (lastReviewTime.getYear() == now.getYear() && 
            lastReviewTime.getMonth() == now.getMonth()) {
            return Result.error("本月已经审核过");
        }
    }
    
    // 清空用户月审记录表
    usermounthlogService.remove(null);
    
    // 获取第一条shareBit记录
    Double shareBit = sharebitService.list().get(0).getShareBit();
    
    // 获取所有用户
    List<User> users = userService.list();
    
    for (User user : users) {
        // 计算比率
        Double ratio = user.getUpdateNum() / (user.getDownloadNum() == 0 ? 1.0 : user.getDownloadNum());
        
        // 根据比率比较设置monthCheck
        user.setMonthCheck(ratio > shareBit ? "0" : "1");
        
        // 更新用户信息
        userService.updateById(user);
        
        // 在用户月审记录中插入一条这个用户的月审记录
        usermounthlogService.save(Usermounthlog.builder()
            .uid(user.getId())
            .content(ratio < shareBit ? "月考核达标" : "月考核不达标，您的分享率为:"+ratio+",请你使用保种积分来兑换被下载数量，之后重新提交审核")
            .build());
    }
    
    // 创建新的月审记录
    mouthlogService.save(Mouthlog.builder()
        .createTime(LocalDateTime.now())
        .uid(id)
        .build());
    return Result.success();
}

@GetMapping("/submitMounthCheck")
public Result submitMounthCheck(@RequestParam Long id) {
    // 获取用户信息
    User user = userService.getById(id);
    if (user == null) {
        return Result.error("用户不存在");
    }
    
    // 获取shareBit阈值
    Double shareBit = sharebitService.list().get(0).getShareBit();
    
    // 计算需要的下载量
    Double updateNum = Double.valueOf(user.getUpdateNum());
    int requiredDownloadNum = (int) Math.ceil(updateNum / shareBit);
    
    // 计算需要的保种积分
    int neededSeedPoints = requiredDownloadNum - user.getDownloadNum();
    
    // 检查保种积分是否足够
    if (user.getSeekPoint() < neededSeedPoints) {
        // 保种积分不足，降低等级
        int currentGrade = user.getGrade();
        if (currentGrade <= 0) {
            return Result.error("级别过低且保种积分不足，无法通过月审");
        }
        
        // 降低等级
        user.setGrade(currentGrade - 1);
        // 更新月审状态
        user.setMonthCheck("1");
        userService.updateById(user);
        
        // 创建月审记录
        usermounthlogService.save(Usermounthlog.builder()
            .uid(id)
            .content("保种积分不足，等级已降低至" + (currentGrade - 1) + "级，月审已通过")
            .build());
            
        return Result.success("等级已降低，月审已通过");
    }
    
    // 扣除保种积分
    user.setSeekPoint(user.getSeekPoint() - neededSeedPoints);
    // 增加下载量
    user.setDownloadNum(user.getDownloadNum() + neededSeedPoints);
    // 更新月审状态
    user.setMonthCheck("1");
    
    // 更新用户信息
    userService.updateById(user);
    
    // 创建月审记录
    usermounthlogService.save(Usermounthlog.builder()
        .uid(id)
        .content("使用" + neededSeedPoints + "点保种积分兑换下载量，月审已通过")
        .build());
    
    return Result.success();
}

        }